from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.saas.scheduling_dates   import scheduling_dates_controller
from app.models import SchedulingDates, SchedulingRules
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.saas import *
from datetime import datetime, timedelta
from app.controllers.appointment.designer import appointment_designer_controller
from collections import defaultdict

saas_scheduling_dates_router = APIRouter()
model_name = "排班"

@saas_scheduling_dates_router.get("/get_week", summary=f"获取某周")
async def do_settings_week(
        week: int = Query(0, description="周时间戳"),
):
    if week > 0:
        # 将时间戳转换为日期对象
        week_in_seconds = week / 1000
        # 将时间戳转换为日期对象
        start_of_week = datetime.fromtimestamp(week_in_seconds)
    else:
        # 如果 week 为 0，使用当前日期
        start_of_week = datetime.now()

        # 计算本周的第一天（周一）
    start_of_week = start_of_week - timedelta(days=start_of_week.weekday())

    # 生成本周的日期列表
    week_dates = [
        {
            "date": (start_of_week + timedelta(days=i)).strftime("%Y-%m-%d"),  # 格式化为 "YYYY-MM-DD"
            "selected": 0  # 默认值为 0
        }
        for i in range(14)  # 生成 14 天的日期
    ]

    return Success(data=week_dates)

@saas_scheduling_dates_router.get("/designers", summary=f"查看员工列表")
async def do_settings_designer(
        page: int = Query(1, description="页码"),
        page_size: int = Query(100, description="每页数量"),
        week: int = Query(0, description="week"),
        space_id: int = Query(1, description="门店id"),
):
    q = Q()
    if space_id:
        q &= Q(space_id__contains=[space_id])

    total, data = await appointment_designer_controller.do_list(page=page, page_size=page_size, search=q)
    # 获取所有设计师的 ID
    designer_ids = [item['id'] for item in data]

    # 获取本周的日期和排班数据
    week_dates, scheduling_dict = await get_week_dates(week, designer_ids,space_id)
    print(week_dates,'week_dates')
    print(scheduling_dict,'scheduling_dict')

    # 为每个设计师生成 dates 数据
    for item in data:
        designer_id = item['id']
        item_dates = []
        for day in week_dates:
            is_select = scheduling_dict.get(designer_id, {}).get(day, 0)
            item_dates.append({
                "date": day,
                "selected": is_select
            })
        item['dates'] = item_dates

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

async def get_week_dates(week, designer_ids,space_id):
    if week > 0:
        # 将时间戳转换为日期对象
        week_in_seconds = week / 1000
        start_of_week = datetime.fromtimestamp(week_in_seconds)
    else:
        # 如果 week 为 0，使用当前日期
        start_of_week = datetime.now()

    # 计算本周的第一天（周一）
    start_of_week = start_of_week - timedelta(days=start_of_week.weekday())

    # 生成本周的日期列表
    week_dates = [
        (start_of_week + timedelta(days=i)).strftime("%Y-%m-%d")
        for i in range(14)  # 生成 14 天的日期
    ]

    # 批量查询 SchedulingDates 表
    scheduling_data = await SchedulingDates.filter(
        date__in=week_dates,
        designer_id__in=designer_ids,
        space_id=space_id
    ).values("date", "designer_id", "rules_id")

    # 将查询结果缓存到字典中
    scheduling_dict = defaultdict(dict)
    for entry in scheduling_data:
        scheduling_dict[entry["designer_id"]][entry["date"]] = entry["rules_id"]

    return week_dates, scheduling_dict


@saas_scheduling_dates_router.get("/list", summary=f"查看{model_name}列表")
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    total, data = await scheduling_dates_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@saas_scheduling_dates_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await scheduling_dates_controller.do_detail(data_id=data_id)
    return Success(data=data)

@saas_scheduling_dates_router.post("/create", summary=f"创建{model_name}")
async def do_settings_create(
        data_in: SchedulingDatesCreate,
):
    rules_id = data_in.rules_id
    rules_data = await SchedulingRules.filter(id=rules_id).first().values("start","end")
    if rules_data:
        data_in.start = rules_data["start"]
        data_in.end = rules_data["end"]
    await SchedulingDates.filter(date=data_in.date,designer_id=data_in.designer_id,space_id=data_in.space_id).delete()
    await scheduling_dates_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@saas_scheduling_dates_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: SchedulingDatesUpdate,
):
    await scheduling_dates_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@saas_scheduling_dates_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await scheduling_dates_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")
